<template>
  <div class="mob-ec-box-card" v-if="useLocale.isMob"></div>
  <div v-else class="box-card" shadow="hover">
    <div class="search-con flex justify-between flex-wrap">
      <el-space wrap :size="10" class="mt-1">
        <el-input
          v-model="params.keyword"
          style="width: 150px"
          placeholder="关键字"
        />
        <el-input
          v-model="params.fb_name"
          style="width: 150px"
          placeholder="标组名称"
        />
        <el-button :icon="Search" plain @click="search">查詢</el-button>
      </el-space>
      <el-space wrap :size="10" class="mt-1">
        <el-button type="danger" plain>删除</el-button>
        <el-button type="info" plain>下载</el-button>
        <el-dropdown>
          <el-button type="primary" plain>
            新增<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>新增商品</el-dropdown-item>
              <el-dropdown-item>选择商品</el-dropdown-item>
              <el-dropdown-item>选择优惠券</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-space>
    </div>
    <div class="px-15">
      <el-table
        ref="dragTable"
        @selection-change="handleSelectionChange"
        :data="tableData"
        row-key="group_id"
        :row-class-name="tableRowClassName"
        class="scroll dragTable"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="selectable"
        ></el-table-column>
        <el-table-column label="排序" align="center" width="100">
          <template #default="scope">
            <el-button v-if="scope.row.status == 0" link type="primary">
              <nut-icon
                font-class-name="iconfont"
                class-prefix="icon"
                size="16"
                name="zhiding"
                @click="toTop(scope.$index, scope.row)"
              ></nut-icon>
            </el-button>
            <span class="px">{{ Number(scope.row.group_sort) + 1 }} </span>
            <el-popover
              placement="top"
              :ref="`popover-${scope.$index}`"
              @before-enter="sortShow(scope.$index, scope.row)"
              :width="200"
              trigger="click"
            >
              <el-form-item label="排序" label-width="60px">
                <el-input-number
                  v-model="data_rel.nSort"
                  :min="data_rel.minSort"
                  :max="data_rel.maxSort"
                  size="small"
                  controls-position="right"
                  @change="handleChange"
                />
                <div class="font-sm text-tips-color">
                  区间 ({{ data_rel.minSort }}-{{ data_rel.maxSort }})
                </div>
              </el-form-item>
              <el-form-item label-width="60px">
                <el-button
                  size="small"
                  type="primary"
                  @click.stop="sortConfirm()"
                >
                  确定
                </el-button>
              </el-form-item>
              <template #reference>
                <el-button
                  class="drag-handler"
                  v-if="scope.row.status == 0"
                  link
                  type="primary"
                >
                  <el-icon size="14"><Sort /></el-icon>
                </el-button>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="关键字" prop="goods_id" />
        <el-table-column prop="group_name" label="标组名称" />
        <el-table-column width="200">
          <template #header>
            <el-space :size="0" :spacer="spacer">
              <span>库存</span>
              <span>价格</span>
              <span>进货价格</span>
            </el-space>
          </template>
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <span>{{ scope.row.group_stock }}</span>
              <span>{{ scope.row.price }}</span>
              <span>{{ scope.row.purchase_price }}</span>
            </el-space>
          </template>
        </el-table-column>
        <el-table-column prop="status_name" label="状态" width="80">
          <template #default="scope">
            <div v-if="scope.row.status == 2">
              <div class="text-tips-color">{{ scope.row.status_name }}</div>
              <div
                class="text-light-color font-sm"
                v-if="scope.row.stop_budan == 1"
              >
                已停止补单
              </div>
            </div>
            <span v-else :class="{ primaryColor: scope.row.status == 1 }">
              {{ scope.row.status_name }}</span
            >
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-space :size="3">
              <el-button link type="info">
                <el-icon size="18"><Edit /></el-icon>
              </el-button>
              <el-button v-if="scope.row.status == 0" link type="danger">
                <el-icon size="18"><Delete /></el-icon>
              </el-button>

              <el-button link type="primary">
                <nut-icon
                  font-class-name="iconfont"
                  class-prefix="icon"
                  size="19"
                  name="qb"
                ></nut-icon>
              </el-button>
              <el-button
                v-if="scope.row.status != 0 && scope.row.stop_budan == 0"
                link
                type="warning"
              >
                <el-icon size="19"><VideoPause /></el-icon>
              </el-button>
              <el-button v-if="scope.row.status != 0" link>
                <nut-icon
                  font-class-name="iconfont"
                  class-prefix="icon"
                  size="19"
                  name="editprice"
                ></nut-icon>
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- <div v-if="total > params.page_size" class="mt-2 flex justify-center">
        <el-pagination
          v-model:current-page="params.current_page"
          v-model:page-size="params.page_size"
          :page-sizes="[500, 1000]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div> -->
      <div class="more" v-if="total > params.page_size">
        <el-button
          link
          :loading="load.loading"
          :disabled="load.disabled"
          type="primary"
          @click="loadMore"
          >{{ load.text }}</el-button
        >
      </div>
    </div>
  </div>
  <el-dialog v-model="dialogFormVisible" title="Shipping address" width="500">
    <el-form :model="form">
      <el-form-item label="Promotion name" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="Zones" :label-width="formLabelWidth">
        <el-select v-model="form.region" placeholder="Please select a zone">
          <el-option label="Zone No.1" value="shanghai" />
          <el-option label="Zone No.2" value="beijing" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick, inject, computed, h } from "vue";
import { $getEmall, $postEmall } from "@api/setting";
import {
  Search,
  ArrowDown,
  Sort,
  Top,
  Edit,
  Delete,
  VideoPause,
} from "@element-plus/icons-vue";
import { useLocaleStore } from "@/store/locales";
import { useCommonStore } from "@/store/common";
import { useI18n } from "vue-i18n";
import { $getGroupList, $groupSort } from "@api/live";
import Sortable from "sortablejs";
const useLocale = useLocaleStore();
const useCommon = useCommonStore();
const reload = inject("reload");
const live_id = inject("liveId");
const live_type = inject("liveType");
const { t } = useI18n();
const langkey = computed(() => useLocale.locale);
let currids = ref([]); //选择的行id
let params = ref({
  group_key: "",
  group_name: "",
  sortby: "", //排序
  current_page: 1,
  page_size: 500,
});

let load = reactive({
  text: "点击加载更多",
  disabled: false,
  loading: false,
});
const data_rel = reactive({
  oSort: "",
  nSort: "",
  minSort: "",
  maxSort: "",
  oTable: [],
  sortAfter: [],
});
const total = ref(0);
const tableData = ref([]);
const dragTable = ref(null);
const spacer = h(ElDivider, { direction: "vertical" });
onMounted(() => {
  getData();
  nextTick(() => {
    initSortable();
  });
});
const getData = async () => {
  currids.value = [];
  let sortArr = [];
  let res = await $getGroupList(params.value);
  load.loading = false;
  console.log(res);
  if (res.code == 0) {
    if (useLocale.isMob) {
      res.data.table.forEach((ele) => {
        Reflect.set(ele, "checked", false);
      });
    }
    tableData.value = [...tableData.value, ...res.data.table];
    console.log(tableData.value);
    tableData.value.forEach((ele) => {
      if (ele.status == 0) {
        sortArr.push(ele.group_sort);
      }
    });
    console.log(sortArr);
    data_rel.minSort = Number(sortArr[0]) + 1;
    data_rel.maxSort = Number(sortArr[sortArr.length - 1]) + 1;
    console.log("min",data_rel.minSort);
    console.log("max",data_rel.maxSort);
    data_rel.oTable = JSON.parse(JSON.stringify(tableData.value));

    total.value = res.data.total;
    if (useLocale.isMob) {
      nextTick(() => {
        scrollbarRef.value.setScrollTop(0);
      });
    }
  }
};

const search = () => {
  getData();
};

const loadMore = () => {
  console.log(params.value.current_page);
  let loadedNums = params.value.current_page * params.value.page_size;
  if (loadedNums >= total.value) {
    load.text = "noData";
    load.disabled = true;
    return false;
  }
  load.loading = true;
  params.value.current_page++;
  getData();
};
const handleSizeChange = (val: number) => {
  params.value.page_size = val;
  getData();
};
const handleCurrentChange = (val: number) => {
  params.value.current_page = val;
  getData();
};
const selectable = (row, index) => {
  if (row.status != 0) {
    return false;
  } else {
    return true;
  }
};
const handleSelectionChange = (val) => {
  currids.value = [];
  if (val.length !== 0) {
    val.forEach((ele) => {
      currids.value.push(ele.fb_user_id);
    });
  }
};
let sortableInstance: Sortable | null = null;
const initSortable = () => {
  nextTick(() => {
    const table = dragTable.value.$el.querySelector(
      ".el-table__body-wrapper tbody"
    );
    // const table = document.querySelector('.reqtable .el-table__body-wrapper tbody') // 使用这种方法路由切换后再切换回来获取不到
    if (sortableInstance) {
      sortableInstance.destroy();
    }
    sortableInstance = new Sortable(table, {
      draggable: ".drag-row ",
      handle: ".drag-handler",
      touchStartThreshold: 20,
      ghostClass: "sortable-ghost", // 放置占位符的类名
      chosenClass: "sortable-chosen", // 所选项目的类名
      dragClass: "sortable-drag", // 拖动项的类名
      onEnd: (evt) => {
        if (evt.oldIndex !== evt.newIndex) {
          setNodeSort(evt);
          console.log(
            "拖动成功",
            `元素拖动前索引${evt.oldIndex}---元素拖动后索引${evt.newIndex}`
          );
        }
      },
    });
  });
};
const tableRowClassName = ({ row, rowIndex }) => {
  if (row.status == 0) {
    return "drag-row";
  } else {
    return "";
  }
};

const setNodeSort = (evt) => {
  //使用arr复制一份表格数组数据
  let idxArr = [evt.oldIndex, evt.newIndex];
  let sortParams = [];
  idxArr = idxArr.sort((a, b) => a - b);
  console.log("idx:", idxArr);
  // let cutArr=data_rel.oTable.slice(idxArr[0], idxArr[1]+1)
  // let cutSortArr = cutArr.map(obj => obj.group_sort);

  data_rel.sortAfter = JSON.parse(JSON.stringify(tableData.value));
  const currentRow = data_rel.sortAfter.splice(evt.oldIndex, 1)[0];
  data_rel.sortAfter.splice(evt.newIndex, 0, currentRow);
  //修改数字排序
  //将排序后的数组区间 sort值 = 排序前数组的sort值
  data_rel.sortAfter.forEach((item, index) => {
    if (index >= idxArr[0] && index <= idxArr[1]) {
      let obj = {
        group_id: item.group_id,
        group_sort: data_rel.oTable[index].group_sort,
      };
      sortParams.push(obj);
      item.group_sort = data_rel.oTable[index].group_sort;
    }
  });
  console.log("sortParams", sortParams);
  console.log("sortAfter:", data_rel.sortAfter);
  console.log("otable:", data_rel.oTable);
  console.log("tablevalue:", tableData.value);
  // 原数组置空
  //xxx = [];
  nextTick(async () => {
    let res = await $groupSort(sortParams);
    console.log(res);
    if (res.code == 0) {
      console.log(res.code);
      tableData.value = data_rel.sortAfter;
      data_rel.oTable = JSON.parse(JSON.stringify(tableData.value));
    } else {
      ElMessage.error(res.msg);
      tableData.value = [...data_rel.oTable];
      //dom 还原
      const tagName = evt.item.tagName;
      const items = evt.from.getElementsByTagName(tagName);
      if (evt.oldIndex > evt.newIndex) {
        evt.from.insertBefore(evt.item, items[evt.oldIndex + 1]);
      } else {
        evt.from.insertBefore(evt.item, items[evt.oldIndex]);
      }
    }
  });
};
const sortShow = (index, row) => {
  data_rel.oSort = Number(row.group_sort);
  data_rel.nSort = Number(row.group_sort) + 1;
};
const toTop = (index, row) => {
  data_rel.oSort = Number(row.group_sort);
  data_rel.nSort = data_rel.minSort;
  sortConfirm();
};
const sortConfirm =async () => {
  // console.log("nsort", data_rel.nSort);
  // console.log("osort", data_rel.oSort);
  if (data_rel.oSort !== data_rel.nSort - 1) {
    let idxArr = [data_rel.oSort, data_rel.nSort - 1];
    let sortParams = [];
    idxArr = idxArr.sort((a, b) => a - b);
    console.log("idx:", idxArr);
    console.log("o",data_rel.oSort);
    console.log("n",data_rel.nSort-1);
    let afterSort = JSON.parse(JSON.stringify(tableData.value));
    const currentRow = afterSort.splice(data_rel.oSort, 1)[0];
    console.log(currentRow);
    afterSort.splice(data_rel.nSort - 1, 0, currentRow);
    console.log("afterSort", afterSort);
    console.log("otable", tableData.value);
    //修改数字排序
    //将排序后的数组区间 sort值 = 排序前数组的sort值
    afterSort.forEach((item, index) => {
      if (index >= idxArr[0] && index <= idxArr[1]) {
        let obj = {
          group_id: item.group_id,
          group_sort: tableData.value[index].group_sort,
        };
        sortParams.push(obj);
        item.group_sort = tableData.value[index].group_sort;
      }
 
    });
    console.log("params",sortParams)
    let res = await $groupSort(sortParams);
      console.log(res);
      if (res.code == 0) {
        console.log(res.code);
       tableData.value = afterSort;
      } else {
        ElMessage.error(res.msg);
      }
  }else{
    console.log("不排序")
  }
};

</script>
<style lang="scss" scoped>
.scroll {
  height: calc(100vh - 200px);
}
.box-card {
  .search-con {
    border-bottom: 1px solid #ededed;
    padding: 5px 5px 15px 15px;
  }
}
.list {
  color: var(--el-text-color-regular);
  .head {
    display: table;
    padding-top: 10px;
    padding-bottom: 12px;
    width: 100%;
    font-size: 14px;

    li {
      display: table-cell;
      box-sizing: border-box;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: normal;
      word-break: break-all;
      line-height: 23px;
      padding: 0 12px;
      font-weight: 600;
      border-bottom: 1px solid #ebebeb;
    }
  }
  .content {
    display: table-row;
    width: 100%;
    font-size: 13px;
    &:nth-child(even) {
      background-color: var(--el-fill-color-lighter); /* 双行交替色 */
    }
    &:hover {
      background-color: #f5f7fa;
    }
    li {
      display: table-cell;
      padding: 8px 0;
      min-width: 0;
      box-sizing: border-box;
      text-overflow: ellipsis;
      vertical-align: middle;
      position: relative;
      z-index: var(--el-table-index);
      border-bottom: 1px solid #ebeef5;
      .cell {
        box-sizing: border-box;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: normal;
        word-break: break-all;
        line-height: 23px;
        padding: 0 12px;
      }
    }
  }
  .more {
    text-align: center;
    font-size: 13px;
    padding: 10px;
    color: #606366;
  }
}
.primaryColor {
  color: var(--el-color-primary);
}
.more {
  text-align: center;
  font-size: 13px;
  padding: 10px;
  color: #606366;
}
.sortable-ghost {
  background: red;
}
.sortable-chosen {
  background: blue;
}
.sortable-drag {
  background: green;
}
</style>
